package com.example.apiproject.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.apiproject.entity.Labels;
import com.example.apiproject.entity.User;
import com.example.apiproject.dao.UserDao;
import com.example.apiproject.dao.LabelsDao;
import com.example.apiproject.entity.form.LoginForm;
import com.example.apiproject.service.UserService;
import com.example.apiproject.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-09-23 13:40:57
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private LabelsDao labelsDao;

    //添加标签
    public User addUserLabel(int userId, List<String> labelNames) {
        List<Labels> existingLabels = new ArrayList<>();
        List<Labels> newLabels = new ArrayList<>();


        for (String labelName : labelNames) {
            Labels label = labelsDao.getLabelByName(labelName);
            if (label == null) {
                // 不存在的标签，添加到新标签列表中
                Labels newLabel = new Labels();
                newLabel.setLabel(labelName);
                newLabel.setCreateTime(DateUtil.date());
                newLabels.add(newLabel);
            } else {
                // 已存在的标签，添加到已存在标签列表中
                existingLabels.add(label);
            }
        }

        if (!newLabels.isEmpty()) {
            // 批量插入新标签到 labels 表
            labelsDao.insertLabels(newLabels);
        }

        List<Labels> allLabels = new ArrayList<>(existingLabels);
        allLabels.addAll(newLabels);

        for (Labels label : allLabels) {
            userDao.addLabelToUser(userId, label.getId());
        }

        return userDao.getUserById(userId);
    }

    //删除标签
    public Integer deleteUserLabel(int userId, int labelId) {
        return userDao.deleteUserLabel(userId, labelId);
    }

    @Override
    public Integer login(LoginForm form) {
        String username = form.getUsername();
        String password = form.getPassword();
        Integer id = userDao.selectIdBynamePassword(username, password);
        return id;
    }

    @Override
    public int register(User form) {
        User user = new User();
        user.setUsername(form.getUsername());
        user.setPassword(form.getPassword());
        user.setPhone(form.getPhone());
//        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//        Date date1 = new Date();
//        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//
//        try {
//
//            Date date = df.parse(formatter.format(date1)); //Mon Jan 14 00:00:00 CST 2013
//            user.setCreateTime(date);
//        } catch (ParseException e) {
//
//            e.printStackTrace();
//
//        }

        UUID uuid = UUID.randomUUID();
//        user.setId(uuid.toString());
        user.setCreateTime(DateUtil.date());
        return userDao.insert(user);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        User user = userDao.queryById(id);
//        List<Labels> labels = userDao.getLabelsByUserId(id);
////      列表存储labels，方便前端进行遍历
//        List<String> labelName = new ArrayList<>();
//        for (Labels label : labels){
//            labelName.add(label.getLabel());
//        }
////        System.out.println(labelName);
//        user.setLabels(labels);
        return user;
    }

    /**
     * 分页查询
     *
     * @param user        筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<User> queryByPage(User user, PageRequest pageRequest) {
        long total = this.userDao.count(user);
        return new PageImpl<>(this.userDao.queryAllByLimit(user, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userDao.insert(user);
        return user;
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
//    @Override
//    public User update(User user) {
//        this.userDao.update(user);
//        return this.queryById(user.getId());
//    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userDao.deleteById(id) > 0;
    }

    @Override
    public User findUser(LoginForm form) {
        return this.userDao.findUser(form);
    }
}
